package de.tudresden.st.cbse.calendar.user;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@Remote(RemoteUserManager.class)
public class UserManagerBean implements RemoteUserManager {
    
    @PersistenceContext
    EntityManager em;

    @Override
    public boolean register(String email, String name, String password) {
        if (name == null || name.isEmpty() || email == null || email.isEmpty() || password == null || password.isEmpty())
            return false;
        
        return this.register(new User(name, email, password));
    }

    @Override
    public boolean register(User user) {
        if (user == null)
            return false;
        
        if (em.find(User.class, user.getEmail()) != null)
            return false;
        
        em.persist(user);
        return true;
    }

    @Override
    public boolean authenticate(String email, String password) {
        if (email == null || email.isEmpty() || password == null || password.isEmpty())
            return false;
        
        User user = em.find(User.class, email);
        
        return ((user != null) && user.check(password));
    }
}
